//express项目生成器自动生成
var express = require('express');
var path = require('path');
const multer = require('multer');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

//自己导入路由
var indexRouter = require('./routes/index');
var userRouter = require('./routes/user');
var testRouter = require('./routes/test')
var cateRouter = require('./routes/cate')
var goodRouter = require('./routes/good')   
var flavorRouter = require('./routes/flavor')
var shoppingRouter = require('./routes/shopping')
var favoriteRouter = require('./routes/favorite')
var admainRouter = require('./routes/admain')

var app = express();


const bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

const { expressjwt: expressJWT } = require('express-jwt'); // 修改这里

// 定义 secret 密钥
const secretKey = 'itheima No1 ^_^';

// 注册将 JWT 字符串解析还原成 JSON 对象的中间件
app.use(expressJWT({ secret: secretKey, algorithms: ['HS256'] }).unless({ path: [/^\/api\// , '/user/login','/admain/login','/admain/register','/user/register',/^\/images\/.*/ ] }));

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));



// 设置存储位置和文件命名规则
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, 'uploads/'); // 保存到 uploads 目录
    },
    filename: function (req, file, cb) {
      cb(null, Date.now() + '-' + file.originalname); // 文件名包含时间戳
    }
  });
  
  // 创建 multer 实例
  const upload = multer({ storage: storage });

  // 设置上传路由
app.post('/upload', upload.single('file'), (req, res) => {
  // req.file 包含上传的文件信息
  const filePath = req.file.path;
  const fileName = path.basename(filePath);
  const url = `/images/${fileName}`;
  // 返回文件的 URL
  res.status(200).json({ message: 'File uploaded successfully.', url: url });
});

// 静态文件服务
app.use('/images', express.static(path.join(__dirname, 'uploads')));
console.log(" express.static(path.join(__dirname, 'uploads'))", express.static(path.join(__dirname, 'uploads')))
// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});


// 解决跨域问题
app.all("*",function(req,res,next){
    // 设置允许跨域的域名,*代表允许任意域名跨域
    res.header('Access-Control-Allow-Origin','*');
    // 允许的header类型
    res.header('Access-Control-Allow-Headers','content-type');
    // 跨域允许的请求方式
    res.header('Access-Control-Allow-Methods','DELETE,PUT,POST,GET,OPTIONS');
    if(req.method.toLowerCase() == 'options')
        res.send(200); // 让options 尝试请求快速结束
    else
        next();
})
const cors = require('cors')
app.use(cors())

// express项目生成器自动生成
// 可自己添加路由
app.use('/', indexRouter);
app.use('/user', userRouter);
app.use('/test',testRouter)
app.use('/cate',cateRouter)
app.use('/good',goodRouter)
app.use('/flavor',flavorRouter)
app.use('/shopping',shoppingRouter)
app.use('/favorite',favoriteRouter)
app.use('/admain',admainRouter)

module.exports = app;
